package org.convallaria.framework.security.filter;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.convallaria.framework.security.config.AnonymousPathRegistry;
import org.convallaria.framework.security.config.SecurityProperties;
import org.convallaria.framework.security.core.JwtTokenProvider;
import org.convallaria.framework.security.core.SecurityUser;
import org.convallaria.framework.security.service.TokenService;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * JWT认证过滤器
 * 从请求中提取JWT token并进行认证
 * 
 * @author convallaria
 * @since 1.0.0
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtTokenProvider jwtTokenProvider;
    private final SecurityProperties securityProperties;
    private final TokenService tokenService;
    private final AnonymousPathRegistry anonymousPathRegistry;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, 
                                  FilterChain filterChain) throws ServletException, IOException {
        
        String requestURI = request.getRequestURI();
        
        // 检查是否为匿名访问路径
        if (anonymousPathRegistry.isAnonymousPath(requestURI)) {
            log.debug("跳过JWT验证，匿名访问路径: {}", requestURI);
            filterChain.doFilter(request, response);
            return;
        }
        
        // 从请求中获取token
        String token = resolveToken(request);
        
        if (token != null && !token.trim().isEmpty()) {
            try {
                // 验证token
                if (jwtTokenProvider.validateToken(token) && tokenService.validateToken(token)) {
                    // 解析token
                    Claims claims = jwtTokenProvider.parseToken(token);
                    SecurityUser securityUser = jwtTokenProvider.buildSecurityUser(claims);
                    
                    // 设置认证信息
                    UsernamePasswordAuthenticationToken authentication = 
                            new UsernamePasswordAuthenticationToken(securityUser, null, 
                                    securityUser.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    
                    // 设置到SecurityContext
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                    
                    log.debug("用户 {} 认证成功", securityUser.getUsername());
                }
            } catch (ExpiredJwtException e) {
                log.warn("Token已过期: {}", e.getMessage());
                // 可以在这里处理token刷新逻辑
            } catch (Exception e) {
                log.error("Token认证失败: {}", e.getMessage());
            }
        }
        
        filterChain.doFilter(request, response);
    }

    /**
     * 从请求中解析token
     * 
     * @param request HTTP请求
     * @return token字符串
     */
    private String resolveToken(HttpServletRequest request) {
        String bearerToken = request.getHeader(securityProperties.getJwt().getHeader());
        
        if (bearerToken != null && !bearerToken.trim().isEmpty() && 
            bearerToken.startsWith(securityProperties.getJwt().getPrefix())) {
            return bearerToken.substring(securityProperties.getJwt().getPrefix().length());
        }
        
        // 也可以从请求参数中获取token（可选）
        String paramToken = request.getParameter("token");
        if (paramToken != null && !paramToken.trim().isEmpty()) {
            return paramToken;
        }
        
        return null;
    }

}
